package com.chagee.store.operation.server.task;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.date.TimeInterval;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.alibaba.arms.tracing.Span;
import com.alibaba.arms.tracing.Tracer;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.chagee.store.operation.server.model.bo.StoreInfoBO;
import com.chagee.store.operation.server.model.param.QueryStoreParam;
import com.chagee.store.operation.server.service.GenerateStoreSettlementData;
import com.chagee.store.operation.server.service.base.StoreBaseService;
import com.xxl.job.core.biz.model.ReturnT;
import com.xxl.job.core.handler.annotation.XxlJob;
import com.xxl.job.core.log.XxlJobLogger;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.*;
import java.util.stream.Collectors;

/**
 *
 * 未打烊扣罚 = 500*已过期状态工单
 * 合格率扣罚 = 底价/当月天数 * 不合格工单(评分<80)个数
 *
 *  支付金额 = 门店设置的结算底价 - 未打烊扣罚 - 合格率扣罚 - 离职人员扣罚(待定) -稽核扣罚 - 其他扣罚
 *
 * 生成结算单
 * @Author : hk
 * @Date : 2024/10/16
 */

@Component
@Slf4j
public class AutoGenerateSettlementHandler {

	@Resource
	private StoreBaseService storeBaseService;

	@Resource
	private GenerateStoreSettlementData generateStoreSettlementData;

	/**
	 * 自动创建结算单 0 0 12 4 * ?
	 * 每月4日12点执行
	 *
	 * @param param
	 * @return
	 */
	@XxlJob("autoGenerateSettlementHandler")
	public ReturnT<String> autoGenerateSettlementHandler(String param) {
		Span span = Tracer.builder().getSpan();
		TimeInterval timer = DateUtil.timer();
		log.info("自动结算单定时任务开始,traceId :{}", span.getTraceId());
		try {

			if (StrUtil.isNotEmpty(param)) {
				log.info("param: {}", param);
				Map map = Optional.ofNullable(JSONUtil.toBean(param, Map.class)).orElse(new HashMap(16));
				String storeNo = String.valueOf(map.get("storeNo"));
				List<String> storeCodeList = Arrays.stream(storeNo.split(",")).map(String::trim).filter(StringUtils::isNotBlank).collect(Collectors.toList());
				String cycle = String.valueOf(map.get("cycle"));

				List<StoreInfoBO> storeInfoBOList = storeBaseService.batchQueryStoreList(storeCodeList);
				for (StoreInfoBO storeInfoBO : storeInfoBOList) {
					log.info("storeDOS: {}", JSONObject.toJSONString(storeInfoBO));
					Boolean aBoolean = false;
					try {
						aBoolean = generateStoreSettlementData.generateData(storeInfoBO, cycle);
					} catch (Exception e) {
						log.error("门店{},创建结算单异常: ", storeInfoBO.getStoreNo(), e);
					}
					log.info("门店{},创建结算单完成: {}", storeInfoBO.getStoreNo(), aBoolean);
				}
			}else {
				long startIndex = 0L;
				while (true) {
					QueryStoreParam queryStoreParam = new QueryStoreParam();
					queryStoreParam.setStartIndex(startIndex);
					List<StoreInfoBO> storeDOS = storeBaseService.queryStoreList(queryStoreParam);

					log.info("startIndex:{},storeInfoBOList:{}", startIndex, JSONObject.toJSONString(storeDOS));
					if (CollectionUtils.isEmpty(storeDOS)) {
						break;
					}
					List<String> storeNoList = storeDOS.stream().map(StoreInfoBO::getStoreNo).collect(Collectors.toList());
					log.info("查询配置打烊开启的门店:{}", JSON.toJSONString(storeNoList));

					for (StoreInfoBO storeDO : storeDOS) {
						log.info("门店{},创建结算单开始", storeDO.getStoreNo());
						Boolean generateData = false;
						try {
							generateData = generateStoreSettlementData.generateData(storeDO,"");
						} catch (Exception e) {
							//接告警
							log.error("门店{},创建结算单异常: ", storeDO.getStoreNo(), e);
						}
						log.info("门店{},创建结算单完成: {}", storeDO.getStoreNo(), generateData);
					}
					startIndex = Math.toIntExact(storeDOS.stream().map(StoreInfoBO::getId).max(Comparator.naturalOrder()).orElse(0L));
				}
			}
		} catch (Exception e) {
			XxlJobLogger.log("自动创建结算单定时任务异常，异常信息:", e);
			log.error("自动创建结算单定时任务异常 => param : {} => 异常信息 : ", param, e);
		}
		XxlJobLogger.log("自动创建结算单定时任务结束，共耗时:{}", timer.intervalRestart());
		return ReturnT.SUCCESS;
	}

}
